// 路由守卫
import router from '@/router'
import store from '@/store'

router.beforeEach(async(to, from, next) => {
  // 是否登陆
  if (store.getters.token) {
    // 已登录
    // 是否去登录页
    if (to.path === '/login') {
      // next 如果传入url可以跳转页面
      next('/')
    } else {
      if (!Object.keys(store.getters.yonghuxx).length) {
        await store.dispatch('user/getUserInfo')
        const menus = await store.dispatch('permission/getPerm')
        router.addRoutes([
          ...menus,
          {
            path: '*',
            component: () => import('@/views/404'),
            hidden: true
          }
        ])
        return next(to.path)
      }
      next()
    }
  } else {
    // 未登录
    // 判断是否在允许非登陆用户访问白名单中
    const whiteList = ['/login', '/registered', '/404', '/test']
    if (whiteList.indexOf(to.path) !== -1) {
      // 在白名单随便进
      next()
    } else {
      next('/login')
    }
  }
})
